﻿using System;

namespace BorgExt
{
    internal static class ArrayEx
    {
        internal static T[] Add<T>(T[] oldElements, T element)
        {
            if (oldElements == null)
                return new[] {element};

            var elements = new T[oldElements.Length + 1];

            Array.Copy(oldElements, 0, elements, 0, oldElements.Length);
            elements[oldElements.Length] = element;
            
            return elements;
        }

        internal static T[] Insert<T>(T[] oldElements, int index, T element)
        {
            if (oldElements == null)
                return new[] {element};

            var elements = new T[oldElements.Length + 1];

            if (index == 0)
            {
                elements[0] = element;
                Array.Copy(oldElements, 0, elements, 1, oldElements.Length);
            }
            else
            {
                Array.Copy(oldElements, 0, elements, 0, index);
                elements[index] = element;
                Array.Copy(oldElements, index, elements, index + 1, oldElements.Length - index);
            }

            return elements;
        }

        internal static T[] Remove<T>(T[] oldElements, T element)
        {
            if (oldElements == null)
                return null;

            if (oldElements.Length == 1)
                return oldElements[0].Equals(element)
                    ? null
                    : oldElements;

            var index = Array.IndexOf(oldElements, element, 0, oldElements.Length);
            
            return index < 0
                ? oldElements
                : RemoveAt(oldElements, index);
        }

        internal static T[] RemoveAt<T>(T[] oldElements, int index)
        {
            var elements = new T[oldElements.Length - 1];

            Array.Copy(oldElements, 0, elements, 0, index);
            Array.Copy(oldElements, index + 1, elements, index, elements.Length - index);

            return elements;
        }
    }
}

